﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreClientModule;

namespace MBBStoreClient
{
    public partial class frmLogin : Form
    {
        UserManager um = new UserManager();
        public frmLogin()
        {
            InitializeComponent();
            um.ProcessCompleted += new ModuleEventsHandler(um_ProcessCompleted);
            um.ProcessError += new ModuleEventsHandler(um_ProcessError);
            btnLogin.Click += new EventHandler(btnLogin_Click);
            txtUsername.KeyPress += new KeyPressEventHandler(txtUsername_KeyPress);
            txtPassword.KeyPress += new KeyPressEventHandler(txtPassword_KeyPress);
        }

        void um_ProcessError(int procCode, string msg)
        {
            uCoreClasses.uThreader t = new uCoreClasses.uThreader();
            t.SafeCall(this, delegate
            {
                //lblNotice.Text = msg;
                MessageBox.Show(msg);
            });
        }

        void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnLogin_Click(null, null);
            }
        }

        void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                txtPassword.Focus();
            }
        }


        void btnLogin_Click(object sender, EventArgs e)
        {
            lblNotice.Text = "Logging In. Please wait...";
            UserType ut = new UserType();
            ut.Username = txtUsername.Text;
            ut.Password = txtPassword.Text;
            um.Login(ut);
        }

        void um_ProcessCompleted(int procCode, string msg)
        {
            uCoreClasses.uThreader t = new uCoreClasses.uThreader();
            t.SafeCall(this, delegate
            {
                if (um.User.logged)
                {
                    Common.Username = um.User.Username;
                    Common.Password = um.User.Password;
                    Common.UserLogged = um.User.logged;
                    txtUsername.Text = "";
                    txtPassword.Text = "";
                    Common.parent.LoginUser(Common.Username);
                    this.Close();
                }
                else
                {
                    lblNotice.Text = "Invalid username or password.";
                    txtUsername.Text = "";
                    txtPassword.Text = "";
                    txtUsername.Focus();
                }
            });
        }
    }
}
